package Studing;

/**
 * @ClassName SingleList
 * @Description: 单链表
 * @Author hl
 * @Date 2020/5/31
 * @Version V1.0
 **/
class Node{
    int val;
    Node next;
    public Node(int val, Node next) {
        this.val = val;
        this.next = next;
    }
    public Node(int val) {
        this.val = val;
        this.next=null;
    }
}

public class SingleList {
    //头结点
    Node head=null;
    int size=0;


    /*添加节点尾插法*/
public void addNode(int val){
    Node newNode=new Node(val);
    if(head==null){
        head=newNode;
        return;
    }
    Node temp=head;
    while(temp.next!=null){
        temp=temp.next;
    }
    temp.next=newNode;
    size++;
}

/*删除节点*/
public boolean deleteNode(int val){
    //如果链表是空链表，返回false
    if(size<=0){
        return  false;
    }

    Node temp=head;

    //删除头结点
    if(head.val==val){
        head=head.next;
        size--;
        return true;
    }
    //正常删除节点
    while(temp.next!=null){
        if(temp.next.val==val){
            break;
        }
        temp=temp.next;
    }

    if(temp.next==null){
        return false;
    }
    Node targer=temp.next;
    temp.next=targer.next;
    size--;
    return true;

}

/*添加节点位于某个节点之后*/
public void addNode(Node p,int val){
    Node temp=head;
    while(temp!=null){
        if(temp==p){
            Node newNode=new Node(val);
            newNode.next=temp.next;
            temp.next=newNode;
            return;
        }
        temp=temp.next;
    }
}

public  void  printNode(){
    Node temp=head;
    while(temp!=null){
        System.out.println(temp.val);
        temp=temp.next;
    }
}


    public static void main(String[] args) {
        SingleList singleList=new SingleList();
        singleList.addNode(1);
        singleList.addNode(2);
        singleList.addNode(5);
        singleList.deleteNode(5);
        singleList.printNode();
    }

}
